package com.nanuminc.market.today.detail;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.nanuminc.market.NMConstants;
import com.nanuminc.market.R;
import com.nanuminc.market.common.TimeLineAdapter;
import com.nanuminc.market.common.TimeLineList;
import com.nanuminc.market.mapsearch.MyIconItemizedOverlay;
import com.nanuminc.market.utils.DomParserUtil;
import com.nanuminc.market.utils.ImageUtil;
import com.nanuminc.market.utils.XMLUtil;

public class TodayDetailView extends MapActivity implements
		OnItemSelectedListener, OnItemClickListener {
	// 1tab
	TextView product_info_text;

	// 2tab
	TextView location_info_text;
	MapView mapView;
	MapController mc;
	List<Overlay> overlay;
	String mProvider;
	String locXml;
	/** Google에서 현재 주소 가져오는 xml */
	String currentAddress;
	/** 현재위치 주소 */

	Drawable mMappin;
	Location currentLocation; // 현재 위치
	LocationManager mLocMan;
	MyLocationOverlay2 mLocation;

	GeoPoint currentGP;
	/** 현재좌표 지오포인터 */

	DomParserUtil parser = new DomParserUtil();
	/** dom parser */

	int totalListNum;
	static double currentLatitude, currentLongitude;
	/** 현재위치 좌표 */

	/** 맵에 표시된 오버레이를 가지고있는 리스트. */
	List<Overlay> listOverlays;

	// 3tab
	TextView postscript_text;
	ListView postscript_list;
	TextView title_left, title_center, title_right;
	ArrayList<TimeLineList> arItem;
	Context context;
	TimeLineAdapter myAdapter;
	ListView mainList;
	int UpdateFlag = 0;
	int itemNum = 0;
	LinearLayout mAddView;
	boolean addview = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.todaydetailview);

		context = getApplicationContext();

		// 해상도 문제 시작 <--
		int dip_Width, dip_Height;
		dip_Width = this.getWindowManager().getDefaultDisplay().getWidth();
		dip_Height = this.getWindowManager().getDefaultDisplay().getHeight();

		Gallery gallery = (Gallery) findViewById(R.id.productgallery);

		if (dip_Width == 720 && dip_Height == 1280)
			gallery.setAdapter(new ImageUtil(this, "HIGH"));
		else
			gallery.setAdapter(new ImageUtil(this));

		findViewById(R.id.imagebtn1).setOnClickListener(mClickListener);
		findViewById(R.id.imagebtn2).setOnClickListener(mClickListener);
		findViewById(R.id.imagebtn3).setOnClickListener(mClickListener);

		title_left = (TextView) findViewById(R.id.btn_location);
		title_center = (TextView) findViewById(R.id.btn_title);
		title_right = (TextView) findViewById(R.id.btn_search);
		title_left.setVisibility(View.INVISIBLE);
		title_right.setVisibility(View.INVISIBLE);
		title_center.setText(getString(R.string.detail));

		product_info_text = (TextView) findViewById(R.id.text_product_infomation);
		mapView = (MapView) findViewById(R.id.mapview);
		location_info_text = (TextView) findViewById(R.id.text_location_infomation);
		postscript_text = (TextView) findViewById(R.id.text_postscript);
		postscript_list = (ListView) findViewById(R.id.list_postscript);

		DetailViewProductInfo();

		// 2tab
		mapView.setSatellite(false); // 위성지도 사용여부 true면 위성지도
		mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// 사용가능한 적절한 프로바이더를 받아온다.
		// network (보통 3G망,Wifi AP 위치정보)또는 gps 둘중 하나로 설정된다.
		mProvider = mLocMan.getBestProvider(new Criteria(), true);
		currentLocation = mLocMan.getLastKnownLocation(mProvider);

		mc = mapView.getController();
		mc.setZoom(17);

		mLocation = new MyLocationOverlay2(this, mapView);

		mLocMan.requestLocationUpdates(mProvider, 2, 3, mLocationListener);

		updateOverlay(currentLocation);

		gallery.setOnItemSelectedListener(this);
		gallery.setOnItemClickListener(this);
	}

	/**
	 * 겔러리 이동해서 현재가운데 있는 상태
	 */
	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		Log.e("hyup2", "onItemSelected param : " + position + " " + id);

	}

	@Override
	public void onNothingSelected(AdapterView<?> view) {
		// TODO Auto-generated method stub

	}

	/**
	 * 겔러리 클릭했을때 루틴
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Log.e("hyup2", "setOnItemClickListener param : " + position + " " + id);
	}

	void DetailViewProductInfo() {
		title_right.setVisibility(View.INVISIBLE);
		// 1tab
		product_info_text.setVisibility(View.VISIBLE);
		product_info_text.setText(getString(R.string.productinfo));
		// 2tab
		mapView.setVisibility(View.INVISIBLE);
		location_info_text.setVisibility(View.INVISIBLE);
		// 3tab
		postscript_text.setVisibility(View.INVISIBLE);
		postscript_list.setVisibility(View.INVISIBLE);
		UpdateFlag = 1;
	}

	void DetailViewLocationInfo() {
		title_right.setVisibility(View.INVISIBLE);
		// 1tab
		product_info_text.setVisibility(View.INVISIBLE);
		// 2tab
		mapView.setVisibility(View.VISIBLE);
		location_info_text.setVisibility(View.VISIBLE);

		// 3tab
		postscript_text.setVisibility(View.INVISIBLE);
		postscript_list.setVisibility(View.INVISIBLE);
		UpdateFlag = 1;
	}

	void DetailViewPostscript() {

		title_right.setVisibility(View.VISIBLE);
		title_right.setText(getString(R.string.write));
		// 1tab
		product_info_text.setVisibility(View.INVISIBLE);
		// 2tab
		mapView.setVisibility(View.INVISIBLE);
		location_info_text.setVisibility(View.INVISIBLE);
		// 3tab
		postscript_text.setVisibility(View.VISIBLE);
		postscript_list.setVisibility(View.VISIBLE);

		// Timeline 리스트 호출
		createThreadAndDialog();
		mAddView = (LinearLayout) View.inflate(this, R.layout.addview, null);
		UpdateFlag = 1;
	}

	private ProgressDialog loagindDialog; // Loading Dialog

	void createThreadAndDialog() {
		/* ProgressDialog */
		/* ProgressDialog */
		loagindDialog = ProgressDialog.show(this, "로딩 중", "잠시만 기다려 주세요....",
				true, false);

		Thread thread = new Thread(new Runnable() {
			public void run() {

				// HttpPostTimeLine();
				arItem = new ArrayList<TimeLineList>();

				totalListNum = 15; // test;
				if (totalListNum > 10) {
					for (itemNum = 0; itemNum < 10; itemNum++) {

						/**
						 * TimeLineList value 순서
						 * 
						 * int timeLineType; // type String listName; // 제목
						 * String listContants; // 내용 String updateTime; // 등록
						 * 시간 String listType; // 내용 타입 Bitmap listImg; // 이미지
						 * String favo; // 즐겨찾기
						 */

						arItem.add(new TimeLineList(
								NMConstants.POSTSCRIPT_LIST, "noiddd",
								"여기좀좋네요..ㅎㅎ 대박임 또올께옄ㅋ", "2012.05.23 13:08",
								null, null, null, false));
					}
				} else {
					for (itemNum = 0; itemNum < totalListNum; itemNum++) {
						arItem.add(new TimeLineList(
								NMConstants.POSTSCRIPT_LIST, "noiddd",
								"여기좀좋네요..ㅎㅎ 대박임 또올께옄ㅋ", "2012.05.23 13:08",
								null, null, null, false));
					}
				}

				handler.sendEmptyMessage(0);

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		});
		thread.start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loagindDialog.dismiss();

			myAdapter = new TimeLineAdapter(context, arItem);
			mainList = (ListView) findViewById(R.id.list_postscript);

			mAddView.setVisibility(View.INVISIBLE);
			if (!addview) {
				addview = true;
				mainList.addFooterView(mAddView);
			}

			if (UpdateFlag == 1) {
				myAdapter.notifyDataSetChanged();
			}
			mainList.setAdapter(myAdapter);
			// if(tokpo == 0) tokpo++; // TestLine
			// mainList.setSelectionFromTop(tokpo, 0); // 0326 Append, Good

			mainList.setOnScrollListener(new OnScrollListener() {

				@SuppressWarnings("unchecked")
				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub
					if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
						Log.v("nanum", "IN, totalItemCount = " + totalItemCount);

						if (totalListNum > itemNum) {
							mAddView.setVisibility(View.VISIBLE);
							new getMoreItems().execute(arItem);
						} else {
							mAddView.setVisibility(View.INVISIBLE);
						}

						Log.v("nanum", "IN END");
					}
				}

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub

				}

			});
		}
	};

	protected void updateOverlay(Location location) {
		if (location != null) {
			currentGP = new GeoPoint((int) (location.getLatitude() * 1000000),
					(int) (location.getLongitude() * 1000000));

			currentLatitude = location.getLatitude();
			currentLongitude = location.getLongitude();

			locXml = XMLUtil.getXml("http://maps.google.co.kr/maps/geo?q="
					+ currentLatitude + "," + currentLongitude
					+ "&output=xml&sensor=false&key=");

			// dom parser
			currentAddress = parser
					.getNode(0, parser.getNodeList(
							parser.getDomElement(locXml), "address"));
			Log.e("nanum", "현재위치 : " + currentAddress);

			/** 현재위치 overlay add */
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.icon_mypoint);
			// bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
			Drawable drawable = new BitmapDrawable(bitmap);
			MyIconItemizedOverlay mdio = new MyIconItemizedOverlay(drawable);
			OverlayItem overlayitem = new OverlayItem(currentGP, "", "");
			mdio.addOverlayItem(overlayitem);
			overlay = mapView.getOverlays();
			overlay.add(mdio);
		}
	}

	void LocationInfoMapView() {
		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(true);
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mc = mapView.getController();

		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2, 3,
				mLocationListener);
	}

	Button.OnClickListener mClickListener = new Button.OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.imagebtn1:
				DetailViewProductInfo();
				break;

			case R.id.imagebtn2:
				DetailViewLocationInfo();
				location_info_text.setText(getString(R.string.locationinfo));
				break;

			case R.id.imagebtn3:
				if (arItem != null) {
					mainList = null;
					mainList = (ListView) findViewById(R.id.list_postscript);
					arItem.clear();

				}
				totalListNum = 0;
				DetailViewPostscript();
				postscript_text.setText("여기는 후기다!! 버럭!!!");
				break;

			default:
				break;
			}
		}
	};

	LocationListener mLocationListener = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {
			String sStatus = "";
			switch (status) {
			case LocationProvider.OUT_OF_SERVICE:
				sStatus = "범위 벗어남";
				break;
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
				sStatus = "일시적 불능";
				break;
			case LocationProvider.AVAILABLE:
				sStatus = "사용 가능";
				break;
			}
			Log.e("hyup2", provider + "상태변경 :" + sStatus);

		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
		}

		public void onLocationChanged(Location location) {
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.removeUpdates(mLocationListener);
	}

	class MyLocationOverlay2 extends MyLocationOverlay {
		public MyLocationOverlay2(Context context, MapView mapView) {
			super(context, mapView);
			// TODO Auto-generated constructor stub
		}
	}

	private class getMoreItems extends
			AsyncTask<ArrayList<TimeLineList>, Integer, Long> {

		@Override
		protected Long doInBackground(ArrayList<TimeLineList>... params) {
			// TODO Auto-generated method stub
			Long result = 0L;

			if (totalListNum >= itemNum + 10) {
				int tmpEnd = itemNum + 10;

				Log.v("nanum", "if > itemNum = " + itemNum);

				for (; itemNum < tmpEnd; itemNum++) {
					arItem.add(new TimeLineList(NMConstants.POSTSCRIPT_LIST,
							"noiddd", "여기좀좋네요..ㅎㅎ 대박임 또올께옄ㅋ",
							"2012.05.23 13:08", null, null, null, false));
				}
			} else {
				Log.v("nanum", "else ");
				for (; itemNum < totalListNum; itemNum++) {
					arItem.add(new TimeLineList(NMConstants.POSTSCRIPT_LIST,
							"noiddd", "여기좀좋네요..ㅎㅎ 대박임 또올께옄ㅋ",
							"2012.05.23 13:08", null, null, null, false));
				}
			}
			Log.v("nanum", "changed!!");

			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				;
			} // 1초 지연. 네트워크 작업 등을 시뮬레이션

			return null;
		}

		public void onPostExecute(Long result) {
			myAdapter.notifyDataSetChanged();

		}
	}
}